import React, { useState, useEffect } from "react";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import Navbar from "../Navbar.jsx";
import Sidebar from "../Sidebar.jsx";
import axios from "axios";
import { FaTachometerAlt } from "react-icons/fa";
import Select from "react-select";
import LoadingScreen from "../../Loading.jsx";

const DiscountCouponForm = () => {
  const navigate = useNavigate();
  const [isSidebarOpen, setSidebarOpen] = useState(true);
  const [loading, setLoading] = useState(false);
  const [searchParams] = useSearchParams();
  const couponid = searchParams.get("couponid");

  const [formData, setFormData] = useState({
    occasionName: "",
    expiryDate: "",
    value: 0,
    couponType: "",
    description: "",
    status: "Active",
  });

  const couponTypeOptions = [
    { label: "Percentage(%)", value: "percentage" },
    { label: "Fixed", value: "fixed" },
    { label: "Value", value: "value" },
  ];

  useEffect(() => {
    if (window.innerWidth < 768) {
      setSidebarOpen(false);
    }
  }, []);

  const fetchDiscountCoupon = async () => {
    if (!couponid) return;
    try {
      setLoading(true);
      const response = await axios.get(`https://mybackend-l7om.onrender.com/api/discount-coupons/${couponid}`, {
        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      });
      if (response.data) {
        setFormData({
          occasionName: response.data.occasionName || "",
          expiryDate: response.data.expiryDate ? new Date(response.data.expiryDate).toISOString().split("T")[0] : "",
          value: response.data.value || 0,
          couponType: response.data.couponType || "",
          description: response.data.description || "",
          status: response.data.status || "Active",
        });
      }
    } catch (err) {
      alert(`Failed to fetch coupon: ${err.response?.data?.error || err.message}`);
      console.log("Fetch error:", err.response?.data || err.message);
    } finally {
      setLoading(false);
    }
  };

  const createDiscountCoupon = async () => {
    try {
      setLoading(true);
      const payload = {
        occasionName: formData.occasionName,
        expiryDate: formData.expiryDate,
        value: formData.value,
        couponType: formData.couponType,
        description: formData.description,
        status: formData.status,
      };
      console.log("Payload being sent:", payload);
      console.log("Token:", localStorage.getItem("token"));
      const response = await axios.post("https://mybackend-l7om.onrender.com/api/discount-coupons", payload, {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      alert("Discount coupon added successfully");
      navigate("/coupon-master");
    } catch (err) {
      alert(`Unable to add discount coupon: ${err.response?.data?.error || err.message}`);
      console.log("Error details:", err.response?.data || err.message);
    } finally {
      setLoading(false);
      setFormData({
        occasionName: "",
        expiryDate: "",
        value: 0,
        couponType: "",
        description: "",
        status: "Active",
      });
    }
  };

  const updateDiscountCoupon = async () => {
    try {
      setLoading(true);
      const payload = {
        occasionName: formData.occasionName,
        expiryDate: formData.expiryDate,
        value: formData.value,
        couponType: formData.couponType,
        description: formData.description,
        status: formData.status,
      };
      console.log("Payload being sent for update:", payload);
      const response = await axios.put(`https://mybackend-l7om.onrender.com/api/discount-coupons/${couponid}`, payload, {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      alert("Discount coupon updated successfully");
      navigate("/coupon-master");
    } catch (err) {
      alert(`Unable to update discount coupon: ${err.response?.data?.error || err.message}`);
      console.log("Error details:", err.response?.data || err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (couponid) {
      fetchDiscountCoupon();
    }
  }, []);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: e.target.type === "number" ? Number(value) : value,
    }));
  };

  const handleCouponTypeChange = (selectedOption) => {
    setFormData((prev) => ({
      ...prev,
      couponType: selectedOption ? selectedOption.value : "",
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!formData.occasionName || !formData.expiryDate || !formData.value || !formData.couponType) {
      alert("Please fill all required fields!");
      return;
    }
    if (couponid) {
      updateDiscountCoupon();
    } else {
      createDiscountCoupon();
    }
  };

  if (loading) return <LoadingScreen />;

  return (
    <div className="flex flex-col h-screen">
      <Navbar isSidebarOpen={isSidebarOpen} setSidebarOpen={setSidebarOpen} />
      <div className="flex flex-grow">
        <Sidebar isSidebarOpen={isSidebarOpen} />
        <div className={`flex-grow p-4 min-h-screen transition-all duration-300 ${isSidebarOpen ? "ml-64" : "ml-0"}`}>
          <header className="flex flex-col items-center justify-between h-auto p-4 mb-6 bg-gray-100 rounded-lg shadow-md md:flex-row">
            <h1 className="text-2xl font-semibold">Add/Update Coupon</h1>
            <div className="flex items-center space-x-2 text-blue-600">
              <Link to="/" className="flex items-center text-sm text-gray-500 no-underline hover:text-cyan-600">
                <FaTachometerAlt className="mr-2 text-gray-500 hover:text-cyan-600" /> Home
              </Link>
              <span className="text-gray-400">{">"}</span>
              <Link to="/discount-coupons" className="text-sm text-gray-500 no-underline hover:text-cyan-600">
                Discount Coupons
              </Link>
              <span className="text-gray-400">{">"}</span>
              <span className="text-sm text-gray-500">Discount Coupon</span>
            </div>
          </header>
          <form className="flex flex-col p-4 space-y-4 bg-white border-t-4 rounded-lg shadow-md border-cyan-500" onSubmit={handleSubmit}>
            <div className="flex items-center gap-4">
              <label className="w-1/3 text-sm font-medium text-right">
                Occasion Name <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                className="w-2/3 p-2 border rounded focus:ring focus:ring-blue-300"
                name="occasionName"
                value={formData.occasionName}
                onChange={handleChange}
                placeholder=""
              />
            </div>
            <div className="flex items-center gap-4">
              <label className="w-1/3 text-sm font-medium text-right">
                Expire Date <span className="text-red-500">*</span>
              </label>
              <input
                type="date"
                className="w-2/3 p-2 border rounded focus:ring focus:ring-blue-300"
                name="expiryDate"
                value={formData.expiryDate}
                onChange={handleChange}
              />
            </div>
            <div className="flex items-center gap-4">
              <label className="w-1/3 text-sm font-medium text-right">
                Coupon Value <span className="text-red-500">*</span>
              </label>
              <input
                type="number"
                className="w-2/3 p-2 border rounded focus:ring focus:ring-blue-300"
                name="value"
                value={formData.value}
                onChange={handleChange}
              />
            </div>
            <div className="flex items-center gap-4">
              <label className="w-1/3 text-sm font-medium text-right">
                Coupon Type <span className="text-red-500">*</span>
              </label>
              <Select
                options={couponTypeOptions}
                className="w-2/3"
                value={couponTypeOptions.find(option => option.value === formData.couponType)}
                onChange={handleCouponTypeChange}
                placeholder="Select coupon type"
              />
            </div>
            <div className="flex items-center gap-4">
              <label className="w-1/3 text-sm font-medium text-right">Description</label>
              <textarea
                className="w-2/3 p-2 border rounded focus:ring focus:ring-blue-300"
                name="description"
                value={formData.description}
                onChange={handleChange}
              />
            </div>
            <div className="flex items-center gap-4">
              <label className="w-1/3 text-sm font-medium text-right">Status</label>
              <select
                className="w-2/3 p-2 border rounded focus:ring focus:ring-blue-300"
                name="status"
                value={formData.status}
                onChange={handleChange}
              >
                <option value="Active">Active</option>
                <option value="Inactive">Inactive</option>
              </select>
            </div>
            <div className="flex justify-end gap-4">
              <button
                type="button"
                className="px-4 py-2 text-white bg-gray-500 rounded hover:bg-gray-600"
                onClick={() => navigate("/coupon-master")}
              >
                Cancel
              </button>
              <button
                type="submit"
                className="px-4 py-2 text-white bg-cyan-500 rounded hover:bg-cyan-600"
              >
                {couponid ? "Update Coupon" : "Add Coupon"}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default DiscountCouponForm;